package com.mzba.zxdlyllp.db;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

/**
 * 
 * @author 06peng
 *
 */
public class BookTable {

	public String TABLE_NAME = "book_tb";
	public static final String _id = "_id";
	public static final String TITLE = "title";
	public static final String CONTENT = "content";
	
	private DBManagerImpl db = null;
	
	public BookTable(Context context) {
		if (db == null) {
			db = DBManager.get(context);
		}
		if (!db.isTableExits(db.getConnection(), TABLE_NAME)) {
			createTable();
		}
	}
	
	
	public void createTable() {
		String createTableSql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME
				+ "(_id integer primary key autoincrement, "  + TITLE + " VARCHAR," + CONTENT + " BLOB)";
		db.creatTable(db.getConnection(), createTableSql, TABLE_NAME);
		
	}
	
	public void save(BookEntity entity) {
		try {
			ContentValues value = new ContentValues();
			value.put(TITLE, entity.getTitle());
			value.put(CONTENT, entity.getContent());
			db.save(db.getConnection(), TABLE_NAME, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void save(ArrayList<BookEntity> list) {
		try {
			ArrayList<ContentValues> values = new ArrayList<ContentValues>();
			for (BookEntity entity : list) {
				ContentValues value = new ContentValues();
				value.put(TITLE, entity.getTitle());
				value.put(CONTENT, entity.getContent());
				values.add(value);
			}
			db.saveAll(db.getConnection(), TABLE_NAME, values);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public ArrayList<BookEntity> get() {
		ArrayList<BookEntity> list = new ArrayList<BookTable.BookEntity>();
		Cursor cursor = null;
		try {
			cursor = db.find(db.getConnection(), "select * from " + TABLE_NAME, null);
			if (cursor != null) {
				while (cursor.moveToNext()) {
					BookEntity entry = new BookEntity();
					entry.setTitle(cursor.getString(cursor.getColumnIndex(TITLE)));
					entry.setContent(cursor.getBlob(cursor.getColumnIndex(CONTENT)));
					list.add(entry);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != cursor) {
				cursor.close();
				cursor = null;
			}
		}
		return list;
	}
	
	public void clearTable() {
		db.delete(db.getConnection(), TABLE_NAME, null, null);
	}
	
	public class BookEntity {
		private String title;
		private byte[] content;
		public String getTitle() {
			return title;
		}
		public void setTitle(String title) {
			this.title = title;
		}
		public byte[] getContent() {
			return content;
		}
		public void setContent(byte[] content) {
			this.content = content;
		}
	}
}
